<?php

/*
 * File: anaylysis/check.class.php
 * Author:      jack@yeahcpa.com
 * Date:        2011-10-09
 * Intro:       用于查看session中是否存在需要清理的数据
 * Man:         $check = new YeahTraceCheck();
 *              $check->Run();
 */

//路径设置
include('path.inc.php');

include(PATH . 'includes/class/session.class.php');

define('MAX_IDLE_TIME', 60 * 60);     //最大空闲时间(秒)
define('MAX_RECORD_NUM', 100);      //最大记录数

class YeahTraceCheck
{
    private $sessions = array();

    //数据库连接初始化
    //服务器状态检测
    function __construct(){
        $stats = new YeahTraceMemcache();
        $this->Clear($stats);
    }

    //运行接口函数
    //负责session列表检查
    public function Run(){
        if($this->sessions == array() && 0 == $this->GetSessions()){
            return FALSE;
        }

        foreach($sessions['content'] as $session_id){
            if(IsTimeOut($session_id)){
                $this->Analysis($session_id);
            }
        }
    }

    //从数据库获取全部运行中session
    //返回数据格式:
    //  array(
    //      'count' => session数量,
    //      'content' => array(session id 数组)
    //      )
    private function GetSessions(){
        $this->sessions = array(
            'count' => 0,
            'countent' => array()
        )

        //读取数据库内容，改写sessions
        return $this->sessions['count'];
    }

    //session过期检测
    //超过MAX_IDLE_TIME设定的session返回true
    private function IsTimeOut($session_id){
        $session = new YeahTraceSession($session_id);

        if(MAX_IDLE_TIME <= (time() - $session->last_active)){
            return TRUE;
        }

        return FALSE;
    }

    //memcached内存使用超过50%
    private function Clear($stats){
        if($stats < 0.3){
            return;
        }

        if($this->sessions == array()){
            $this->sessions = $this->GetSessions();
        }

        //根据负载清理memcached内存
        $clear_rate = 0.2;
        if($stats < 0.5){
            $clear_rate = 0.3;
        } elseif ($stats < 0.6) {
            $clear_rate = 0.4;
        } elseif ($stats < 0.7) {
            $clear_rate = 0.5;
        } elseif ($stats < 0.8) {
            $clear_rate = 0.6;
        }

        $cache_count = floor($clear_rate * $this->sessions['count']);
        for($clear = 0; $clear < $cache_count; ++$clear){
            $session_id = $this->sessions['content'][$clear];
            $session = new YeahTraceSession($session_id);
            $session->Cache2File();
            $session->Free();
        }

    }

    //超过最大空闲时间的session,调用anaylsis.php进行分析
    private function Analysis($session_id){
    }

}

?>
